import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from tree.models import TreeDia, TreeDiaSerializer, Tree, TreeSerializer


# Create your views here.
# 查询所有数据
class ListView(View):
    def get(self, req):
        obj_list = TreeDia.objects.all().values()  # .values() 转成字典
        return JsonResponse({'code': 200, 'data': list(obj_list)})  # 把外层的容器转为List后返回


# class GetTreeDia(View):
#     # 根据tree id获取信息
#     def get(self, req):
#         tree = Tree.objects.get(id=int(req.GET['tree_id']))
#         obj = TreeDia.objects.filter(tree=tree)
#         if len(obj) != 0:
#             dias = TreeDiaSerializer(obj, many=True).data
#             # print('@GetTreeDia', dias)
#             for item in dias:
#                 if item['part'] == '带皮直径':
#                     daipi = item
#                 if item['part'] == '皮厚':
#                     pihou = item
#                 if item['part'] == '去皮直径':
#                     qupi = item
#             return JsonResponse({'code': 200, 'daipi': daipi, 'pihou': pihou, 'qupi': qupi})
#         else:
#             return JsonResponse({'code': 500, 'msg': '查询不到数据！'})

class GetTreeDia(View):
    def get(self, req):
        try:
            tree = Tree.objects.get(id=int(req.GET['tree_id']))
            obj = TreeDia.objects.filter(tree=tree)

            if len(obj) != 0:
                # 初始化所有变量
                daipi = None
                pihou = None
                qupi = None

                dias = TreeDiaSerializer(obj, many=True).data

                for item in dias:
                    if item['part'] == '带皮直径':
                        daipi = item
                    elif item['part'] == '皮厚':
                        pihou = item
                    elif item['part'] == '去皮直径':
                        qupi = item

                return JsonResponse({'code': 200, 'daipi': daipi, 'pihou': pihou, 'qupi': qupi})
            else:
                return JsonResponse({'code': 500, 'msg': '查询不到数据！'})

        except Tree.DoesNotExist:
            return JsonResponse({'code': 500, 'msg': '树木不存在！'})
        except Exception as e:
            return JsonResponse({'code': 500, 'msg': f'系统错误: {str(e)}'})


# 获取未录入直径的样木信息
class GetNoDiaTree(View):
    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data.get('pageNum', 1)  # 当前页，如果不存在则默认为1
        pageSize = data.get('pageSize', 10)  # 每页大小
        query = data.get('query', '')  # 查询参数

        obj_dia = TreeDia.objects.all()
        dia_tree_ids = [obj.tree.id for obj in obj_dia]
        # print(dia_tree_ids)
        obj_NoDiaTree = Tree.objects.exclude(id__in=dia_tree_ids)

        # 分页
        paginator = Paginator(obj_NoDiaTree, pageSize)
        dataPage = paginator.page(pageNum)

        print(len(obj_NoDiaTree), TreeSerializer(obj_NoDiaTree, many=True).data)
        return JsonResponse({'code': 200, 'total': len(obj_NoDiaTree),
                             'data': TreeSerializer(dataPage, many=True).data})  # 把外层的容器转为List后返回


# 信息查询
class SearchView(View):
    def post(self, req):
        print(req)
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数

        # 获取查询集
        queryset = TreeDia.objects.filter(part__icontains=query)
        total = queryset.count()

        # 分页
        paginator = Paginator(queryset, pageSize)
        dataPage = paginator.page(pageNum)

        # 序列化数据 - 传递查询集给序列化器
        serializer = TreeDiaSerializer(dataPage.object_list, many=True)

        # dataPage = Paginator(Tree.objects.filter(number__icontains=query), pageSize).page(pageNum)
        # # data = list(dataPage.object_list.values())  # 先转成字典，再转成列表
        # total = Tree.objects.filter(number__icontains=query).count()

        return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})


class ActionView(View):
    # 根据id获取信息
    def get(self, req):
        obj = TreeDia.objects.get(id=req.GET.get('id'))
        return JsonResponse({'code': 200, 'data': TreeDiaSerializer(obj).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        TreeDia.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})


# 新增或修改
class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        tree = Tree.objects.get(id=data['tree'])
        dia = TreeDia.objects.filter(tree=data['tree'], part=data['part'])
        print('@@@dia', dia)
        if data['id'] and not dia:  # 添加
            obj = TreeDia(tree=tree, part=data['part'],
                          p0=data['p0'], p05=data['p05'], p1=data['p1'], p2=data['p2'],
                          p3=data['p3'], p4=data['p4'], p5=data['p5'], p6=data['p6'],
                          p7=data['p7'], p8=data['p8'], p9=data['p9'], volume=data['volume'],
                          remark=data['remark'])
            obj.create_time = datetime.now().date()
            print('save')
            obj.save()
        else:  # 修改
            obj = TreeDia(id=data['id'], tree=tree, part=data['part'],
                          p0=data['p0'], p05=data['p05'], p1=data['p1'], p2=data['p2'],
                          p3=data['p3'], p4=data['p4'], p5=data['p5'], p6=data['p6'],
                          p7=data['p7'], p8=data['p8'], p9=data['p9'], volume=data['volume'],
                          remark=data['remark'])
            obj.update_time = datetime.now().date()
            obj.save()
            print('update')
        return JsonResponse({'code': 200, 'msg': '执行成功！'})
